package com.remote.server.handle;


import com.remote.common.context.listener.ReadListener;
import com.remote.common.model.Request;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Cool-Coding 2018/7/24
 */
@ChannelHandler.Sharable
public class ServerChannelHandler  extends SimpleChannelInboundHandler<Request> {

    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ServerChannelHandler.class);

    private ReadListener<Request> readListener;

    public ServerChannelHandler(ReadListener<Request> readListener) {
        this.readListener = readListener;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Request request) {
        LOGGER.debug(request.toString());
        if (readListener != null) {
            readListener.onRead(ctx, request);
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.error(cause.getMessage(), cause);
        ctx.close();
    }

}
